package com.example.demo.common;

import com.example.demo.entity.DBTypeEnum;

import java.util.concurrent.atomic.AtomicInteger;
import lombok.extern.slf4j.Slf4j;

/**
 * 通过ThreadLocal将数据源设置到每个线程上下文中
 */
@Slf4j
public class DBContextHolder {

    private static final ThreadLocal<DBTypeEnum> contextHolder = new ThreadLocal<>();

    private static final AtomicInteger counter = new AtomicInteger(-1);

    public static void set(DBTypeEnum dbType) {
        contextHolder.set(dbType);
    }

    public static DBTypeEnum get() {
        return contextHolder.get();
    }

    public static void master() {
        set(DBTypeEnum.MASTER);
        System.out.println("切换到master");
    }

    /* 当有多个从库时，可以做一个轮询或随机，选择连接哪个从库 */
    public static void slave() {
        set(DBTypeEnum.SLAVE1);
        System.out.println("切换到slave1");

    }

}
